//
//  BTEHomeViewController.swift
//  BTE
//
//  Created by Mike Zhang on 2025/8/5.
//

import UIKit
import Alamofire


extension Notification.Name {
    static let loginSuccess = Notification.Name("LoginSuccessNotification")
    static let logout = Notification.Name("LogoutNotification")
}


class BTEHomeViewController: BTEBaseViewController {
    
    fileprivate let server = BTEMeToolNetServer()
    fileprivate let pserver = BTEProductToolNetServer()
    let reachMa = NetworkReachabilityManager()
    
    fileprivate var model: BTsidelingwiseModel? {
        didSet {
            guard let m = model else {
                return
            }
            v.model = m
        }
    }
    
    var v: BTEHomeView {
        return view as! BTEHomeView
    }
    
    override func loadView() {
        view = BTEHomeView()
    }

    fileprivate var islogin: Bool {
        let lo = UserDefaults.standard.value(forKey: USER_TOKEN) as? String
        return (lo ?? "").count > 0
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        NotificationCenter.default.addObserver(self, selector: #selector(handleLoginSuccess), name: .loginSuccess, object: nil)

        NotificationCenter.default.addObserver(self, selector: #selector(handleLogout), name: .logout, object: nil)
        
        setNavigationBarHidden(true)
        
        if BTELanguageManager.shared.currentLanguage == .YINNI {
            LocationService.shared.requestLocationInfo { result in
                switch result {
                case .success((_, let info)):
                    LocationUploader.upload(info)
                case .failure(let error):
                    LocationService.shared.presentPermissionAlertIfNeeded()
                }
            }
        }
        
        
        v.list.snp.remakeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalToSuperview()
            
            let keyWindow = UIApplication.shared.connectedScenes
                   .compactMap { $0 as? UIWindowScene }
                   .flatMap { $0.windows }
                   .first { $0.isKeyWindow }

               let bottomInset = keyWindow?.safeAreaInsets.bottom ?? 0
            make.bottom.equalToSuperview().offset(-(bottomInset+63))
        }
        
        v.clickkf = {[weak self] st in
            BTEUrlToolsManager.shared.handleURL(st, in: self, model: nil)
        }
        
        v.lickcpro = {[weak self] st in
            BTEUrlToolsManager.shared.handleURL(st, in: self, model: nil)
        }
        
        v.clickurlx = {[weak self] st in
            if !(self?.islogin)!{
                let login = BTEBaseNavigationViewController.init(rootViewController: BTELoginViewController())
                login.modalPresentationStyle = .overFullScreen
                self?.present(login, animated: true)
                return
            }
            BTEHUD.shared.showLoader(on: (self?.view)!)
            self?.pserver.Carneol(data: ["privileger":st]) {[weak self] result in
                switch result {
                case .success(let success):
                    BTEHUD.shared.hide()
                    BTEUrlToolsManager.shared.handleURL(success?.sidelingwise?.vyner ?? "", in: self, model: nil)
                    break
                case .failure(let failure):
                    switch failure {
                    case .Error(c: let b, m: let bd):
                        BTEHUD.shared.showError(bd, on: (self?.view)!)
                        break
                    default:
                        break
                    }
                    break
                }
            }
        }
        
        v.clickurld = {[weak self] st in
            if !(self?.islogin)!{
                let login = BTEBaseNavigationViewController.init(rootViewController: BTELoginViewController())
                login.modalPresentationStyle = .overFullScreen
                self?.present(login, animated: true)
                return
            }
            
            BTEHUD.shared.showLoader(on: (self?.view)!)
            self?.pserver.Carneol(data: ["privileger":st]) {[weak self] result in
                switch result {
                case .success(let success):
                    BTEHUD.shared.hide()
                    BTEUrlToolsManager.shared.handleURL(success?.sidelingwise?.vyner ?? "", in: self, model: nil)
                    break
                case .failure(let failure):
                    switch failure {
                    case .Error(c: let b, m: let bd):
                        BTEHUD.shared.showError(bd, on: (self?.view)!)
                        break
                    default:
                        break
                    }
                    break
                }
            }
        }
        
        v.clicklist = {[weak self] st in
            if !(self?.islogin)!{
                let login = BTEBaseNavigationViewController.init(rootViewController: BTELoginViewController())
                login.modalPresentationStyle = .overFullScreen
                self?.present(login, animated: true)
                return
            }
            BTEHUD.shared.showLoader(on: (self?.view)!)
            self?.pserver.Carneol(data: ["privileger":st]) {[weak self] result in
                switch result {
                case .success(let success):
                    BTEHUD.shared.hide()
                    BTEUrlToolsManager.shared.handleURL(success?.sidelingwise?.vyner ?? "", in: self, model: nil)
                    break
                case .failure(let failure):
                    switch failure {
                    case .Error(c: let b, m: let bd):
                        BTEHUD.shared.showError(bd, on: (self?.view)!)
                        break
                    default:
                        break
                    }
                    break
                }
            }
        }
        
        v.load = {[weak self] in
            
            switch UIDevice.current.types {
            case .iPad2,
                    .iPad3,
                    .iPad4,
                    .iPadAir,
                    .iPadAir2,
                    .iPadAir3,
                    .iPadAir4,
                    .iPadAir5,
                    .iPad5,
                    .iPad6,
                    .iPad7,
                    .iPad8,
                    .iPad9,
                    .iPad10,

                //iPad Mini
                    .iPadMini,
                    .iPadMini2,
                    .iPadMini3,
                    .iPadMini4,
                    .iPadMini5,
                    .iPadMini6,

                //iPad Pro
                    .iPadPro9_7,
                    .iPadPro10_5,
                    .iPadPro11,
                    .iPadPro2_11,
                    .iPadPro3_11,
                    .iPadPro12_9,
                    .iPadPro2_12_9,
                    .iPadPro3_12_9,
                    .iPadPro4_12_9,
                    .iPadPro5_12_9:
                self?.reachMa?.startListening {[weak self] status in
                    switch status {
                    case .notReachable:
                        self?.v.refreshfunc.endRefreshing()
                        BTEHUD.shared.showError("Network Error", on: (self?.view)!)
                        break
                    case .reachable(.ethernetOrWiFi), .reachable(.cellular):
                        self?.initmodel()
                        self?.inittodoing()
                        break
                    case .unknown:
                       break
                    }
                }
                break
            default:
                self?.initmodel()
                self?.inittodoing()
                break
            }
            
           
        }
        
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        switch UIDevice.current.types {
        case .iPad2,
                .iPad3,
                .iPad4,
                .iPadAir,
                .iPadAir2,
                .iPadAir3,
                .iPadAir4,
                .iPadAir5,
                .iPad5,
                .iPad6,
                .iPad7,
                .iPad8,
                .iPad9,
                .iPad10,

            //iPad Mini
                .iPadMini,
                .iPadMini2,
                .iPadMini3,
                .iPadMini4,
                .iPadMini5,
                .iPadMini6,

            //iPad Pro
                .iPadPro9_7,
                .iPadPro10_5,
                .iPadPro11,
                .iPadPro2_11,
                .iPadPro3_11,
                .iPadPro12_9,
                .iPadPro2_12_9,
                .iPadPro3_12_9,
                .iPadPro4_12_9,
                .iPadPro5_12_9:
            reachMa?.startListening {[weak self] status in
                switch status {
                case .notReachable:
                    self?.v.refreshfunc.endRefreshing()
                    BTEHUD.shared.showError("Network Error", on: (self?.view)!)
                    break
                case .reachable(.ethernetOrWiFi), .reachable(.cellular):
                    self?.initmodel()
                    self?.inittodoing()
                    break
                case .unknown:
                   break
                }
            }
            break
        default:
            initmodel()
            inittodoing()
            break
        }
        
    
    }
    
    @objc private func handleLoginSuccess(_ notification: Notification) {
        switch UIDevice.current.types {
        case .iPad2,
                .iPad3,
                .iPad4,
                .iPadAir,
                .iPadAir2,
                .iPadAir3,
                .iPadAir4,
                .iPadAir5,
                .iPad5,
                .iPad6,
                .iPad7,
                .iPad8,
                .iPad9,
                .iPad10,

            //iPad Mini
                .iPadMini,
                .iPadMini2,
                .iPadMini3,
                .iPadMini4,
                .iPadMini5,
                .iPadMini6,

            //iPad Pro
                .iPadPro9_7,
                .iPadPro10_5,
                .iPadPro11,
                .iPadPro2_11,
                .iPadPro3_11,
                .iPadPro12_9,
                .iPadPro2_12_9,
                .iPadPro3_12_9,
                .iPadPro4_12_9,
                .iPadPro5_12_9:
            reachMa?.startListening {[weak self] status in
                switch status {
                case .notReachable:
                    self?.v.refreshfunc.endRefreshing()
                    BTEHUD.shared.showError("Network Error", on: (self?.view)!)
                    break
                case .reachable(.ethernetOrWiFi), .reachable(.cellular):
                    self?.initmodel()
                    self?.inittodoing()
                    break
                case .unknown:
                   break
                }
            }
            break
        default:
            initmodel()
           inittodoing()
            break
        }
        
    }

    @objc private func handleLogout(_ notification: Notification) {
        switch UIDevice.current.types {
        case .iPad2,
                .iPad3,
                .iPad4,
                .iPadAir,
                .iPadAir2,
                .iPadAir3,
                .iPadAir4,
                .iPadAir5,
                .iPad5,
                .iPad6,
                .iPad7,
                .iPad8,
                .iPad9,
                .iPad10,

            //iPad Mini
                .iPadMini,
                .iPadMini2,
                .iPadMini3,
                .iPadMini4,
                .iPadMini5,
                .iPadMini6,

            //iPad Pro
                .iPadPro9_7,
                .iPadPro10_5,
                .iPadPro11,
                .iPadPro2_11,
                .iPadPro3_11,
                .iPadPro12_9,
                .iPadPro2_12_9,
                .iPadPro3_12_9,
                .iPadPro4_12_9,
                .iPadPro5_12_9:
            reachMa?.startListening {[weak self] status in
                switch status {
                case .notReachable:
                    self?.v.refreshfunc.endRefreshing()
                    BTEHUD.shared.showError("Network Error", on: (self?.view)!)
                    break
                case .reachable(.ethernetOrWiFi), .reachable(.cellular):
                    self?.initmodel()
                    self?.inittodoing()
                    break
                case .unknown:
                   break
                }
            }
            break
        default:
            initmodel()
           inittodoing()
            break
        }
    }


}



fileprivate
extension BTEHomeViewController {
    
    func inittodoing(){
        // 加载地址
        BTEAddressManager.stand.loadAddress()
        
        // stva
        DispatchQueue.main.asyncAfter(deadline: .now()+3){
            BTEDeviceIdentifierManager.shared.requestTrackingAuthorizationIfNeeded { response in
                if response {
                    BTEDeviceIdentifierManager.shared.uploadIDVA()
                }
            }
        }
     
        // location
        LocationService.shared.requestLocationInfo { result in
            switch result {
            case .success((_, let info)):
                LocationUploader.upload(info)
            case .failure(let error):
                print("获取定位失败: \(error)")
                if BTELanguageManager.shared.currentLanguage == .YINNI {
                    LocationService.shared.presentPermissionAlertIfNeeded()
                }
            }
        }
        
        // deviceinfo
        DeviceInfoCollector.collectSummary { info in
            DeviceInfoCollector.uploadInfomation(info)
        }

    }
    
    
    func initmodel(){
        BTEHUD.shared.showLoader(on: view)
        server.sidelingwise {[weak self] result in
            switch result {
            case .success(let success):
                self?.v.refreshfunc.endRefreshing()
                BTEHUD.shared.hide()
                self?.model = success?.sidelingwise
                break
            case .failure(let failure):
                self?.v.refreshfunc.endRefreshing()
                switch failure {
                case .Error(c: let b, m: let bd):
                    BTEHUD.shared.showError(bd, on: (self?.view)!)
                    break
                default:
                    break
                }
                break
            }
        }
    }
    
}

